import { createContext, FC, ReactNode, useContext } from "react"

const EMPTY: unique symbol = Symbol();


interface IContainer<Value> {
  Provider: React.FC,
  useContainer: () => Value
}

export function createContainer<Value>(usehook: () => Value): IContainer<Value> {

  let Content = createContext<Value | typeof EMPTY>(EMPTY)

  const Provider: FC = (props) => {
    const value = usehook()
    return (<Content.Provider value={value}>{props.children}</Content.Provider>)
  }

  function useContainer() {
    const value = useContext(Content)
    if (value === EMPTY) {
      throw new Error("Component must be wrapped with <Container.Provider>")
    }
    return value
  }

  return { Provider, useContainer }
}

